package org.jash.imdemo.fragment;

import android.content.Intent;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.RecyclerView;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.google.android.material.appbar.MaterialToolbar;
import com.hyphenate.EMContactListener;
import com.hyphenate.chat.EMClient;
import com.hyphenate.exceptions.HyphenateException;

import org.jash.imdemo.AddFriendActivity;
import org.jash.imdemo.ChatActivity;
import org.jash.imdemo.R;

import java.util.List;


public class ContactFragment extends Fragment {
    private RecyclerView recycler;
    private ContactAdapter adapter;
    private MaterialToolbar toolbar;
    public ContactFragment() {
        super(R.layout.fragment_contact);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        recycler = view.findViewById(R.id.recycler);
        adapter = new ContactAdapter();
        adapter.setListener(name -> startActivity(new Intent(requireContext(), ChatActivity.class).putExtra("toName", name)));
        recycler.setAdapter(adapter);
        toolbar = view.findViewById(R.id.toolbar);
        toolbar.setOnMenuItemClickListener(item -> {
            startActivity(new Intent(requireContext(), AddFriendActivity.class));
            return true;
        });
        new Thread(() -> {
            try {
                List<String> list = EMClient.getInstance().contactManager().getAllContactsFromServer();
                requireActivity().runOnUiThread(() -> adapter.addAll(list));
            } catch (HyphenateException e) {
                requireActivity().runOnUiThread(() -> Toast.makeText(requireContext(), "获取联系人失败, 原因: " + e.getDescription(), Toast.LENGTH_SHORT).show());
            }
        }).start();

    }
}